package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * ClassName : AccountReceiver
 * Package : com.atguigu.tingshu.account.receiver
 * Description :
 * <p>
 * Author: LHZ
 * Create: 2025/7/20 19:03
 * Version: 1.0
 */
@Component
@Slf4j
public class AccountReceiver {
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private RechargeInfoService rechargeInfoService;

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_USER,durable = "true"),
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER, durable = "true"),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void initUserAccount(Map<String,Object> map, Channel channel, Message message){
        log.info("[账户服务]用户首次注册成功后，为用户初始账户余额记录：{}", map);
        if(map != null){
            userAccountService.initUserAccount(map);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);


    }

    /**
     * 延迟关单 - 充值服务
     * @param rechargeId
     * @param channel
     * @param message
     */
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_CANCEL_ORDER)
    public void cancelRecharge(Long rechargeId, Channel channel,Message message){
        if(rechargeId != null){
            log.info("[充值服务]监听到延迟关单消息：{}", rechargeId);
            //调用充值服务的取消充值方法
            rechargeInfoService.cancelRecharge(rechargeId);
        }
        //确认消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    }

}